import os
import gradio as gr
from openai import OpenAI
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Initialize OpenAI client
client = OpenAI(
    api_key=os.getenv("LLM_API_KEY"),
    base_url=os.getenv("LLM_BASE_URL"),
)

# Global variable to store history
poetry_history = []

def generate_poetry(theme, style):
    if not theme.strip():
        return "请输入有效的主题。"
    prompt = f"Write a poem about {theme} in {style} style. Keep it beautiful and meaningful."
    try:
        response = client.chat.completions.create(
            model=os.getenv("LLM_MODEL"),
            messages=[{"role": "user", "content": prompt}],
            max_tokens=300,
        )
        poetry = response.choices[0].message.content.strip()
        # Format poetry with line breaks
        formatted_poetry = format_poetry(poetry)
        # Add to history
        poetry_history.insert(0, {"theme": theme, "style": style, "poetry": formatted_poetry})
        return formatted_poetry
    except Exception as e:
        return f"生成诗歌时出错：{str(e)}。请检查网络连接或API密钥。"

def format_poetry(poetry):
    """
    Format poetry with proper line breaks and indentation.
    """
    lines = poetry.split('\n')
    # Clean up empty lines and add proper formatting
    formatted_lines = [line.strip() for line in lines if line.strip()]
    # Join with HTML line breaks for better display
    return '<br>'.join(formatted_lines)

def get_history():
    """
    Get formatted history for display.
    """
    if not poetry_history:
        return "暂无历史记录。"
    history_text = ""
    for i, item in enumerate(poetry_history[:5], 1):  # Show last 5
        history_text += f"#{i} 主题: {item['theme']} | 风格: {item['style']}\n"
        history_text += item['poetry'] + "\n\n"
    return history_text

def share_poetry(poetry):
    """
    Simulate sharing - in real app, integrate with actual sharing APIs
    """
    if poetry.strip() and poetry != "暂无诗歌可分享。":
        return f"分享链接已生成：\n{generate_share_link(poetry)}\n\n复制此链接分享您的诗歌！"
    return "暂无诗歌可分享。"

def generate_share_link(poetry):
    """
    Generate a mock share link - in production, use actual URL shortener
    """
    import base64
    encoded = base64.b64encode(poetry.encode('utf-8')).decode('utf-8')
    return f"https://poetry-share.com/share?data={encoded}"

# Create custom CSS for better styling
css = """
.gradio-container {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}
.gr-button {
    background: rgba(255, 255, 255, 0.2) !important;
    border: 1px solid rgba(255, 255, 255, 0.3) !important;
}
.gr-textbox textarea {
    background: rgba(255, 255, 255, 0.1) !important;
    color: white !important;
    border: 1px solid rgba(255, 255, 255, 0.3) !important;
}
.gr-dropdown {
    background: rgba(255, 255, 255, 0.1) !important;
    color: white !important;
}
"""

# Main Gradio interface with tabs
with gr.Blocks(title="AI 诗歌创作", css=css) as iface:
    gr.Markdown("# 🌸 AI 诗歌创作 🌸")
    gr.Markdown("输入主题和风格，生成美丽诗歌。支持多种风格和高级选项。")

    with gr.Tabs():
        # Main generation tab
        with gr.TabItem("创作诗歌"):
            with gr.Row():
                with gr.Column(scale=2):
                    theme_input = gr.Textbox(
                        label="主题 (Theme)",
                        placeholder="输入诗歌主题，如爱情、自然、友谊等",
                        value=""
                    )
                    style_dropdown = gr.Dropdown(
                        label="风格 (Style)",
                        choices=["浪漫的 (Romantic)", "现代的 (Modern)", "古典的 (Classic)", "自由的 (Free verse)", "抒情的 (Lyrical)", "哲理的 (Philosophical)"],
                        value="浪漫的 (Romantic)"
                    )
                    advanced_options = gr.Accordion("高级选项", open=False)
                    with advanced_options:
                        length_slider = gr.Slider(
                            label="诗歌长度 (Length)",
                            minimum=50,
                            maximum=300,
                            value=150,
                            step=25
                        )
                        rhyme_checkbox = gr.Checkbox(label="需要押韵 (Rhyme)", value=False)

                with gr.Column(scale=3):
                    submit_btn = gr.Button("创作诗歌 ✍️", variant="primary")
                    clear_btn = gr.Button("清除 🗑️")
                    output_poetry = gr.HTML(label="生成的诗歌 (Generated Poetry)")

            submit_btn.click(
                fn=lambda t, s, l, r: generate_poetry(t, s + (" with rhyme" if r else "")),  # Note: length not implemented in AI prompt yet
                inputs=[theme_input, style_dropdown, length_slider, rhyme_checkbox],
                outputs=output_poetry
            )
            clear_btn.click(fn=lambda: ("", gr.update(value="浪漫的 (Romantic)"), gr.update(value=150), gr.update(value=False), ""),
                          inputs=[], outputs=[theme_input, style_dropdown, length_slider, rhyme_checkbox, output_poetry])

        # Share tab
        with gr.TabItem("分享诗歌"):
            gr.Markdown("分享您的诗歌给朋友们！")
            share_input = gr.Textbox(label="输入要分享的诗歌", placeholder="粘贴您的诗歌内容")
            share_btn = gr.Button("生成分享链接 🔗")
            share_output = gr.Textbox(label="分享链接", interactive=False)
            share_btn.click(fn=share_poetry, inputs=share_input, outputs=share_output)

        # History tab
        with gr.TabItem("历史记录"):
            gr.Markdown("查看您最近生成的诗歌")
            refresh_btn = gr.Button("刷新历史 📖")
            history_output = gr.Textbox(label="诗歌历史", lines=15, interactive=False)
            refresh_btn.click(fn=get_history, outputs=history_output)

if __name__ == "__main__":
    iface.launch()
